#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# 2021/9/6 15:59
from flask import (
    Blueprint, flash, g, redirect, render_template, request, url_for
)
from werkzeug.exceptions import abort

from flaskr.auth import login_required
from flaskr.db import get_db

bp = Blueprint('blog', __name__)


def get_post(pid, check_author=True):
    post = get_db().execute(
        'SELECT p.id title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' WHERE p.id = ?',
        (pid,)
    ).fetchone()
    if post is None:
        abort(404, f"文章{pid}不存在")
    if check_author and post['author_id'] != g.user['id']:
        abort(403)
    return post


@bp.route('/')
def index():
    db = get_db()
    posts = db.execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id'
        ' ORDER BY created DESC'
    ).fetchall()
    return render_template('blog/index.html', posts=posts)


@bp.route('/create', methods=('GET', 'POST'))
@login_required
def create():
    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

        if not title:
            error = '标题是必填项'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'INSERT INTO post (title, body, author_id)'
                ' VALUES (?, ?, ?)',
                (title, body, g.user['id'])
            )
            db.commit()
            return redirect(url_for('blog.index'))

    return render_template('blog/create.html')


@bp.route('/<int:id>/update', methods=('GET', 'POST'))
@login_required
def update(pid):
    post = get_post(pid)

    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

        if not title:
            error = '标题是必须要填写的'
        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'UPDATE post SET title = ?, body = ? WHERE id = ?',
                (title, body, pid)
            )
            db.commit()
            return redirect(url_for('blog.index'))
    return render_template('blog.html', post=post)


@bp.route('/<int:id>/delete', methods=('POST',))
@login_required
def delete(pid):
    get_post(pid)
    db = get_db()
    db.execute('DELETE FROM post WHERE id = ?', (pid,))
    db.commit()
    return redirect(url_for('blog.index'))

